package com.asiainfo.complier.helper;

import java.awt.Component;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import com.asiainfo.complier.codemanger.CodeManager;
import com.asiainfo.complier.common.CodeInfo;
import com.asiainfo.complier.editor.CoderEditor;
import com.asiainfo.complier.ui.StatusBarItem;

public class DroptargetHelper {

	/***
	 * regsiterDroptarget
	 * 
	 * @param c
	 * @param item
	 * @param manager
	 */
	public void regsiterDroptarget(Component c, final StatusBarItem item,
			final CodeManager manager) {

		new DropTarget(c, new DropTargetAdapter() {

			public void drop(DropTargetDropEvent dtde) {

				if ((dtde.getDropAction() & DnDConstants.ACTION_COPY_OR_MOVE) != 0) {
					// Accept the drop and get the transfer data
					dtde.acceptDrop(dtde.getDropAction());
					Transferable transferable = dtde.getTransferable();
					try {
						boolean result = dropFile(transferable, manager, item);
						dtde.dropComplete(result);
					} catch (Exception e) {

						dtde.dropComplete(false);
					}
				} else {

					dtde.rejectDrop();
				}

			}

		});
	}

	// This method handles a drop for a list of files
	protected boolean dropFile(Transferable transferable, CodeManager manager,
			StatusBarItem item) throws UnsupportedFlavorException, IOException {

		@SuppressWarnings("unchecked")
		List<File> fileList = (List<File>) transferable
				.getTransferData(DataFlavor.javaFileListFlavor);
		for (File transferFile : fileList) {

			String fileText = FileHelper.readFullText(transferFile
					.getAbsolutePath());
			CoderEditor info = manager.addCoderPane(
					transferFile.getAbsolutePath(), fileText, item);
			if (info != null)
				regsiterDroptarget(info.getEditor(), item, manager);
		}

		return true;
	}
}
